package org.singledog.permission.config;


import org.singledog.permission.core.PermissionApplicationContext;
import org.singledog.permission.filter.PermissionCoreFilter;
import org.singledog.permission.filter.PermissionFilter;
import org.singledog.permission.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.*;



/**
 * Permission的核心过滤器注册
 * <p>
 * 如果不想使用此过滤器，请在{@link org.springframework.boot.autoconfigure.SpringBootApplication}
 * 的exclue属性中添加此类{@link PermissionFilterAutoConfiguration}
 * 本例中注册的filter为{@link PermissionCoreFilter}，如需自动扩展请实现{@link PermissionFilter}
 * 此类在{@link PermissionAutoConfiguration}后加载
 *
 * @author liuzheming
 * @since 2021.9.15
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Configuration
@ConditionalOnClass(PermissionCoreFilter.class)
@ConditionalOnBean({PermissionApplicationContext.class,PermissionProperties.class})
@AutoConfigureAfter(PermissionAutoConfiguration.class)
public class PermissionFilterAutoConfiguration {

    private PermissionProperties permissionProperties;

    private PermissionApplicationContext permissionApplicationContext;

    public PermissionFilterAutoConfiguration(PermissionProperties properties, PermissionApplicationContext permissionApplicationContext) {
        this.permissionProperties = properties;
        this.permissionApplicationContext = permissionApplicationContext;
        JwtUtils.setExpireTime(properties.getToken().getExpire());
        JwtUtils.setLoginCount(properties.getLogin().getMaxAddrLogin(), properties.getLogin().getMaxUserLogin());
    }

    /**
     * 注册Permission核心filter
     *
     * @param permissionFilter {@link PermissionCoreFilter}
     * @return {@link FilterRegistrationBean}
     */
    @Bean
    public FilterRegistrationBean<PermissionFilter> registPermissionFilter(@Qualifier("corePermissionFilter") PermissionFilter permissionFilter) {
        FilterRegistrationBean<PermissionFilter> filterFilterRegistrationBean = new FilterRegistrationBean();
        filterFilterRegistrationBean.setFilter(permissionFilter);
        filterFilterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        filterFilterRegistrationBean.addInitParameter("expire", String.valueOf(permissionProperties.getToken().getExpire()));
        permissionApplicationContext.schedule(permissionProperties.getToken().getSchedulePeriod());
        return filterFilterRegistrationBean;
    }

    @Bean("corePermissionFilter")
    public PermissionFilter initPermissionFilter() {
        return new PermissionCoreFilter();
    }
}
